Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

LinkedHashMap → Java LinkedHashMap

LinkedHashMap

Java LinkedHashMap

LinkedHashMap in Java

The LinkedHashMap class in Java extends HashMap and provides a key-value pair storage mechanism that maintains the order in which elements were inserted. This is different from a standard HashMap where the order is not guaranteed. Here are some key characteristics of LinkedHashMap: LinkedHashMap combines the strengths of two popular collection types ⯁ HashMap: Offers fast average constant time (O(1)) lookups, insertions, and deletions due to hashing. However, it doesn't maintain the order elements were added. ⯁ LinkedList: Maintains the insertion order of elements. ⯁ LinkedHashMap: LinkedHashMap implements the Map interface and extends the HashMap class. It uses a hash table for efficient storage and retrieval like HashMap, but it also maintains a doubly-linked list internally to preserve the insertion order of key-value pairs.

Characteristics of LinkedHashMap

Insertion Order: The key feature of LinkedHashMap is that it maintains the order elements were added (insertion order). This is different from HashMap, which is unordered. ⯁ Hashing: Like HashMap, it uses hashing for efficient key-based access. ⯁ Uniqueness: Keys must be unique within a LinkedHashMap. ⯁ Null Keys and Values: Similar to HashMap, it allows storing a single null key and any number of null values.

Declaring and Initializing LinkedHashMaps

Import
linkedhashmap import import java.util.LinkedHashMap;
This line imports the LinkedHashMap class from the java.util package.
Declaration
LinkedHashMap declaration LinkedHashMap<KeyType, ValueType> myMap;
Explanation : This declares a variable named myMap of type LinkedHashMap. The <KeyType> and <ValueType> placeholders specify the data types of the keys and values, respectively.
Initialization Default constructor
Creating empty linkedhashmap myMap = new LinkedHashMap<KeyType, ValueType>();
Explanation : This creates an empty LinkedHashMap object.
Adding elements during creation (Java 7+)
Creating with initial elements LinkedHashMap<String, String> countries = new LinkedHashMap<String, String>(); countries.put("India", "Delhi"); countries.put("USA", "Washington D.C."); countries.put("Canada", "Ottawa");
Explanation : This creates a LinkedHashMap and adds initial key-value pairs while constructing it.

Common LinkedHashMap Methods (same as HashMap):

put(key, value): Inserts a new key-value pair into the map. ⯁ get(key): Returns the value associated with the given key, or null if the key doesn't exist. ⯁ containsKey(key): Checks if the map contains a specific key. ⯁ remove(key): Removes the key-value pair associated with the given key and returns the value. ⯁ isEmpty(): Checks if the map is empty. ⯁ size(): Returns the number of key-value pairs in the map.

Examples for LinkedHashMap in Java

String Keys and Integer Values (Maintaining Task Order)
LinkedHashMap example in java - task priority import java.util.*; public class Main { public static void main(String[] args) { LinkedHashMap<String, Integer> taskPriorities = new LinkedHashMap<>(); taskPriorities.put("Write report", 3); taskPriorities.put("Review code", 2); taskPriorities.put("Fix bugs", 1); for (String task : taskPriorities.keySet()) { System.out.println(task + ": Priority " + taskPriorities.get(task)); } } }

Output

Write report: Priority 3 Review code: Priority 2 Fix bugs: Priority 1
Explanation : This example stores tasks (strings) as keys and their priority levels (integers) as values. The LinkedHashMap ensures tasks are processed based on the order they were added (high to low priority).
Custom Class Keys and String Values (Preserving Order of Recently Accessed Files)
LinkedHashMap example in java - Order of accessed files import java.util.*; class File { String name; long lastAccessed; public File(String name, long lastAccessed) { this.name = name; this.lastAccessed = lastAccessed; } } public class Main { public static void main(String[] args) { LinkedHashMap<File, String> recentFiles = new LinkedHashMap<>(); recentFiles.put(new File("report.txt", System.currentTimeMillis()), "Just edited"); recentFiles.put(new File("image.png", System.currentTimeMillis() - 10000), "Opened recently"); recentFiles.put(new File("code.java", System.currentTimeMillis() - 50000), "Modified earlier"); for (File file : recentFiles.keySet()) { System.out.println(file.name + ": " + recentFiles.get(file)); } } }

Output

report.txt: Just edited image.png: Opened recently code.java: Modified earlier
Explanation : This example defines a File class with name and lastAccessed attributes. LinkedHashMap uses File objects (representing files) as keys and their access status (strings) as values. The order reflects the most recently accessed files first.
Integer Keys and Double Values (Maintaining Order of Price Changes)
LinkedHashMap example in java - order of price changes import java.util.*; public class Main { public static void main(String[] args) { LinkedHashMap<Integer, Double> productPriceHistory = new LinkedHashMap<>(); productPriceHistory.put(123, 199.99); productPriceHistory.put(123, 179.95); productPriceHistory.put(123, 224.50); for (Integer productId : productPriceHistory.keySet()) { System.out.println("Product ID: " + productId + ", Price: $" + productPriceHistory.get(productId)); } } }

Output

Product ID: 123, Price: $224.5
Explanation : This example uses integer product IDs as keys and their corresponding prices (doubles) as values. The LinkedHashMap maintains the order of price changes, allowing you to see the price history for a product.
Remember, LinkedHashMap is flexible with data types as long as the key type properly implements hashCode() and equals() for efficient hashing and comparison. Choose the data types that best suit your specific use case and data storage requirements, keeping in mind the trade-off between order preservation and performance compared to HashMap.

Tutorials